package com.navi.filter;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class InterceptorConfig  implements HandlerInterceptor{    
    
    private static final Logger log = LoggerFactory.getLogger(InterceptorConfig.class);    
    
    /**   
     * 进入controller层之前拦截请求   
     * @param httpServletRequest   
     * @param httpServletResponse   
     * @param o   
     * @return   
     * @throws Exception   
     */    
    @Override    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {    
    
//        log.info("---------------------开始进入请求地址拦截----------------------------");
        HttpSession session = request.getSession();  
        String url = request.getRequestURL().toString();
        String userId = (String) session.getAttribute("userId");
        //用户掉线或被挤掉，保存当前链接并重定向到登录页面
        if (request.getHeader("x-requested-with") == null && !url.endsWith("login") && !url.endsWith("loginOut")) {//非ajax(异步)请求，则保存当前访问链接
            String queryUrl = request.getQueryString() == null ? "" : ("?" + request.getQueryString());//获取参数
            String requestUrl = request.getServletPath() + queryUrl;//httpRequest.getServletPath(),获取链接
            if (session.getAttribute("redirect_link") == null) {
                session.setAttribute("redirect_link", requestUrl);
            }
        }
        //if (StringUtils.isBlank(userId) && !url.endsWith("login")) {
        //    response.sendRedirect(request.getContextPath() + "/login");
        //    return false;
        //}

        return true;
    }    
    
    @Override    
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {    
//        log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }    
    
    @Override    
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {    
//        log.info("---------------视图渲染之后的操作-------------------------0");
    }    
}  